package newschema

import (
	"github.com/lib/pq"
	"github.com/stackrox/rox/generated/storage"
	"github.com/stackrox/rox/pkg/protocompat"
)

// ConvertVulnerabilityRequestFromProto converts a `*storage.VulnerabilityRequest` to Gorm model
func ConvertVulnerabilityRequestFromProto(obj *storage.VulnerabilityRequest) (*VulnerabilityRequests, error) {
	serialized, err := obj.MarshalVT()
	if err != nil {
		return nil, err
	}
	model := &VulnerabilityRequests{
		ID:                                obj.GetId(),
		Name:                              obj.GetName(),
		TargetState:                       obj.GetTargetState(),
		Status:                            obj.GetStatus(),
		Expired:                           obj.GetExpired(),
		RequestorName:                     obj.GetRequestor().GetName(),
		CreatedAt:                         protocompat.NilOrTime(obj.GetCreatedAt()),
		LastUpdated:                       protocompat.NilOrTime(obj.GetLastUpdated()),
		DeferralReqExpiryExpiresWhenFixed: obj.GetDeferralReq().GetExpiry().GetExpiresWhenFixed(),
		DeferralReqExpiryExpiresOn:        protocompat.NilOrTime(obj.GetDeferralReq().GetExpiry().GetExpiresOn()),
		DeferralReqExpiryExpiryType:       obj.GetDeferralReq().GetExpiry().GetExpiryType(),
		CvesCves:                          pq.Array(obj.GetCves().GetCves()).(*pq.StringArray),
		Serialized:                        serialized,
	}
	return model, nil
}

// ConvertSlimUserFromProto converts a `*storage.SlimUser` to Gorm model
func ConvertSlimUserFromProto(obj *storage.SlimUser, idx int, vulnerabilityRequestID string) (*VulnerabilityRequestsApprovers, error) {
	model := &VulnerabilityRequestsApprovers{
		VulnerabilityRequestsID: vulnerabilityRequestID,
		Idx:                     idx,
		Name:                    obj.GetName(),
	}
	return model, nil
}

// ConvertRequestCommentFromProto converts a `*storage.RequestComment` to Gorm model
func ConvertRequestCommentFromProto(obj *storage.RequestComment, idx int, vulnerabilityRequestID string) (*VulnerabilityRequestsComments, error) {
	model := &VulnerabilityRequestsComments{
		VulnerabilityRequestsID: vulnerabilityRequestID,
		Idx:                     idx,
		UserName:                obj.GetUser().GetName(),
	}
	return model, nil
}

// ConvertVulnerabilityRequestToProto converts Gorm model `VulnerabilityRequests` to its protobuf type object
func ConvertVulnerabilityRequestToProto(m *VulnerabilityRequests) (*storage.VulnerabilityRequest, error) {
	var msg storage.VulnerabilityRequest
	if err := msg.UnmarshalVTUnsafe(m.Serialized); err != nil {
		return nil, err
	}
	return &msg, nil
}
